<?php

namespace app\sys\controller;

use app\common\model\UserModel;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;

class User extends Base
{
    private $user_model;
    private $role_model;

    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->user_model = model('common/UserModel');
        $this->role_model = model('common/RoleModel');
    }

    /**
     * @param Request $request
     * @return \think\response\Json|\think\response\View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(Request $request) {
        if (!$request->isAjax()) {
            $data['roles'] = $this->role_model->where('1', '=', 1)->field(['id,name'])->select();
            return view('', $data);
        } else {
            $params = $request->param();
            $search = $params['search'];
            $sort = $params['sort'];
            if ($sort == 'role_name') {
                $sort = 'role.id';
            } else if ($sort == 'id') {
                $sort = 'user.id';
            } else if ($sort == 'create_time') {
                $sort = 'user.create_time';
            } else if ($sort == 'update_time') {
                $sort = 'user.update_time';
            } else if ($sort == 'delete_time') {
                $sort = 'user.delete_time';
            }
            $order = $params['order'];
            $offset = $params['offset'];
            $limit = $params['limit'];

            $role_id = isset($params['role_id']) ? $params['role_id'] : null;

            //拼接查询语句
            $model = $this->user_model->where('1', '=', '1');
            $model->alias('user')->field('user.*,role.name role_name')->join('sys_role role', 'user.role_id = role.id', 'left outer');
            if ($search != null && $search !== '') {
                $model = $model->where('user.name|user.nick|user.address|user.email', 'like', '%' . $search . '%');
            }

            if ($role_id != null && $role_id !== '') {
                $model->where('role_id', '=', $role_id);
            }

            $model = $model->order($sort, $order);
            $model = $model->limit($offset, $limit);
            $data['rows'] = $model->select();
            $data['sql'] = $this->user_model->getLastSql();
            $data['total'] = $model->count();
            $data['search'] = $search;
            $data['sort'] = $sort;
            $data['order'] = $order;
            $data['offset'] = $offset;
            $data['limit'] = $limit;
            return json($data);
        }
    }

    /**
     * @param Request $request
     * @return \think\response\Json|\think\response\View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function add(Request $request) {
        if (!$request->isAjax()) {
            $data['roles'] = $this->role_model->where('1', '=', '1')->field(['id', 'name'])->select();
            return view('', $data);
        } else {
            $user_model = model('common/UserModel');
            $name = $request->param('name');
            $users_exits = $user_model->where('name', '=', $name)->select();
            if (count($users_exits) > 0) {
                return json([
                    'status' => false,
                    'msg' => '用户名不可用'
                ]);
            }
            $email = $request->param('email');
            $users_exits = $user_model->where('email', '=', $email)->select();
            if (count($users_exits) > 0) {
                return json([
                    'status' => false,
                    'msg' => '邮箱不可用'
                ]);
            }
            $user = new UserModel([
                'name' => $name,
                'email' => $email,
                'nick' => $request->param('nick'),
                'gender' => $request->param('gender'),
                'birthday' => $request->param('birthday'),
                'address' => $request->param('address'),
                'role_id' => $request->param('role_id'),
                'password' => md5(trim($request->param('password')))
            ]);

            $user->save();

            return json([
                'status' => true,
                'msg' => '添加成功'
            ]);
        }
    }

    /**
     * @param Request $request
     * @return \think\response\Json|\think\response\View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit(Request $request) {
        if (!$request->isAjax()) {
            $id = $request->param('id');
            $user = $this->user_model->where('id', '=', $id)->find();
            if ($user == null) {
                exit("  ");
            }
            $roles = model('common/RoleModel')->where('1', '=', '1')->select();
            $data['user'] = $user;
            $data['roles'] = $roles;
            return view('', $data);
        } else {
            $user = $this->user_model->where('id', '=', $request->param('id'))->find();
            if ($user == null) {
                return json([
                    'status' => false,
                    'msg' => '对象不存在或已被删除'
                ]);
            }

            $user['nick'] = $request->param('nick');
            $user['gender'] = $request->param('gender');
            $user['birthday'] = $request->param('birthday');
            $user['address'] = $request->param('address');
            $user['role_id'] = $request->param('role_id');
            $password = $request->param('password');
            if ($password != null && $password != '') {
                $user['password'] = md5(trim($password));
            }

            $user['update_time'] = date('Y-m-d H:i:s', time());

            $user->save();
            return json([
                'status' => true,
                'msg' => '修改成功',
                'user' => $user
            ]);
        }
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete(Request $request) {
        $ids = $request->param('ids');
        if ($ids == null) {
            return json([
                'status' => false,
                'msg' => '请传递要删除的IDS'
            ]);
        }

        $idsArray = explode('-', $ids);


        foreach ($idsArray as $id) {
            $user = $this->user_model->where('id', '=', $id)->find();
            if ($user != null) {
                $user['delete_time'] = date('Y-m-d H:i:s', time());
                $user->save();
            }
        }
        return json([
            'status' => true,
            'msg' => '删除成功',
            'ids' => $idsArray
        ]);
    }
}
